/**
 * @desc：关联订单号弹窗
 * @author:binlety
 *
 *
 * * */
import React, { useState, useEffect } from 'react';
import { Button, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import CommonModal from '@/components/CommonModal'
import CommonTable from '@/components/CommonTable'
import CommonLoading from '@/components/CommonLoading'
import { getDeductionRelativeOrderSnOp } from '../service'
import { formatAmount, cpText } from '@/utils/utils.jsx';
import { uniqBy } from 'lodash';


export default ({ records, handleClose }) => {
  const [loading, setLoading] = useState(false);//loading
  const [data, setData] = useState([]);//表格数据
	const navigate = useNavigate();
  useEffect(()=>{
    getRelativeOrderSn();//获取关联订单号
  },[])

  //获取关联订单号
  const getRelativeOrderSn = async () => {
    setLoading(true)
    setData([])
    const { success, data } = await getDeductionRelativeOrderSnOp({payOrderSn:records.payOrderSn})
    if(success){
      setData(data)
    }
    setLoading(false)
  }

  //渲染跳转去页面去订单处理页面的span
  const renderJumptOrderHandle = (orderSn, state) => {
    return <span className='common-color1' style={{cursor:'pointer'}} onClick={()=>publicHandleClick('/views/order/list', orderSn, state)}>{orderSn}</span>
  }

  //公共跳转逻辑
  const publicHandleClick = (pathname, orderSn, erpOrderSrc) => {
    onCancel()
    let timer = setTimeout(() => {
      clearTimeout(timer);
      timer = null;
      navigate(pathname,{ state: {orderSn, erpOrderSrc }});
    },200)
  }

  const columns = [
    {
      title: "唯一码",
      dataIndex: "uniqueCode",
      key: "uniqueCode",
      width: 100,
      render: (text, r) => {
        if(r.amount == 0) {
          return text;
        }
        return <span 
          className='common-color1' 
          style={{cursor:'pointer'}}
          onClick={() => 
            publicHandleClick(
              r.amount < 0 ? `/views/purchase/FmcmPurchase` : `/views/afterSales/FmcmReturns`,
              text
            )
          }
        >
          {text}
        </span>
      }
    },
    {
      title: "商品名称",
      dataIndex: "goodsName",
      key: "goodsName",
      width: 180,
      render: (text, { goodsName, goodsSpec, goodsCode }) => (
        <>
          <div>商品名称：{goodsName}</div>
          <div>规格型号：{goodsSpec}</div>
          <div>商品编码：{goodsCode}</div>
        </>
      )
    },
    {
      title: "数量",
      dataIndex: "goodsNum",
      key: "goodsNum",
      width: 80,
    },
    {
      title:"变动金额",
      dataIndex:"amount",
      key:"amount",
      width: 100,
      render:(text) => {
        if(text){
          if(text.toString().includes('-')){
            return <span className='common-color10'>{formatAmount(text)}</span>
          }else{
            return <span className='common-color9'>+{formatAmount(text)}</span>
          }
        }else{
          return '0.00'
        }
      }
    },
    {
      title:"业务订单号",
      dataIndex:"orderSn",
      key:"orderSn",
      width: 160,
      render:text => renderJumptOrderHandle(text, 2)
    },
  ]

  const hasNum = data.some(item => item.goodsNum > 0);

  //表格
  const TableProps = {
    data,
    columns: hasNum ? columns : columns.filter(item => item.key == 'orderSn' || item.key == 'amount').reverse(),
  }

  //关闭操作
  const onCancel = () => {
    // setData([]) //加上展示效果不好，明显有等待时长
    handleClose()
  }

  const handleFormatAndCopy = (fieldName) => {
    if(data.length > 200){
      message.info('限定最多只能复制200条');
    }
    const copyText = uniqBy(data, fieldName).map((item) => item[fieldName]).slice(0, 200).join(',');
    cpText(copyText);
  }

  return <CommonModal
    title="关联订单号"
    visible={true}
    width='600px'
    onCancel={onCancel}
    footer={[
      <Button key='copyCode' type='primary' shape='round' onClick={() => handleFormatAndCopy('uniqueCode')}>复制唯一码</Button>,
      <Button onClick={() => handleFormatAndCopy('orderSn')} key='copy' type='primary' shape='round'>复制业务订单号</Button>,
      <Button onClick={onCancel} key='close'>关闭</Button>,
    ]}
  >
    <CommonTable { ...TableProps }/>
    <CommonLoading loading={loading}/>
  </CommonModal>
}